<template>
	<scroll-view
		class="scroll-list"
		scroll-y
		:style="{ height }"
		refresher-enabled
		:refresher-triggered="freshing"
		:refresher-background="refresherBackground"
		@refresherrefresh="pullToRefresh"
		@scrolltolower="bottomRefresh"
	>
		<slot>
			<my-empty v-if="status !== 'loading' && !pager.total"></my-empty>
		</slot>
		<u-loadmore v-if="status === 'loading' || pager.total" class="loadmore" :status="status" marginTop="0" marginBottom="0" />
	</scroll-view>
</template>

<script lang="ts" setup>
	import { ref, onMounted, reactive } from 'vue';
	import { throttle } from '@/utils';
	import { Pager } from '@/types/interface';
	
	const emits = defineEmits(['getList', 'initList', 'pullToRefresh']);
	const props = defineProps({
		// 列表高度，必传，不然无法触发下来
		height: {
			type: String,
			default: '',
			require: true,
		},
		// 上拉背景色
		refresherBackground: {
			type: String,
			default: '#f4f5f8',
		},
		// 初始化请求
		init: {
			type: Boolean,
			default: true,
		},
	});
	
	// 下拉刷新状态
	const freshing = ref<boolean>(false);
	// 触底加载状态
	const status = ref<string>('loadmore');
	// 分页器
	const pager = reactive<Pager>({
		pageNum: 1,
		pageSize: 10,
		total: 0,
	});
	
	// 执行成功回调
	const success = (total: number) => {
		const { pageNum, pageSize } = pager;
		freshing.value = false;
		pager.total = total;
		status.value = (pageNum * pageSize >= total) ? 'nomore' : 'loadmore';
	};
	// 获取数据
	const getData = (): void => {
		status.value = 'loading';
		const { total, ...page } = pager;
		emits('getList', page, success);
	};
	// 获取数据-节流
	const getList = throttle(getData, 200);
	// 初始化数据
	const initList = (): void => {
		if (status.value === 'loading') return;
		pager.pageNum = 1;
		emits('initList');
		getList();
	};
	// 下拉刷新
	const pullToRefresh = (): void => {
		if (freshing.value) return;
		freshing.value = true;
		setTimeout(() => initList(), 500);
	};
	// 触底刷新
	const bottomRefresh = (): void => {
		if (status.value === 'loading') return;
		const { pageNum, pageSize, total } = pager;
		if (pageNum * pageSize >= total) return;
		pager.pageNum++;
		getList();
	};
	
	onMounted(() => {
		if (props.init) initList();
	});
	defineExpose({
		status,
		pager: {
			pageNum: pager.pageNum,
			pageSize: pager.pageSize,
		},
		success,
		getList,
		initList,
	});
</script>

<style lang="scss" scoped>
	.scroll-list {
		::v-deep .uni-scroll-view-refresh__spinner {
			circle {
				color: #3E9DBB !important;
			}
		}
		::v-deep .uni-scroll-view-refresh__icon {
			fill: #3E9DBB !important;
		}
		.loadmore {
			padding: 24rpx 0;
		}
	}
</style>
